package myJs.user.mission

import myJs.Implicits._
import myJs.Utils._
import myJs.components.TagComponent

import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.TypedTag
import scalatags.Text.all._
import shared.VarTool

import scala.collection.immutable.SeqMap
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.JSConverters._
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.tool.Pojo.PreDealSoft
import org.scalajs.dom.{Element, document}
import shared.Pojo.MetDataKind


/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("PreDealResult")
object PreDealResult extends MissionResult {

  val importModalId = "importModal"
  val formId = "form"

  @JSExport("init")
  def init = {
    refreshMissionInfo(getMissionId)
    refreshFileInfo(getMissionId)
    registerEvent
    bootStrapValidator
  }

  override def registerEvent: JQuery = {
    super.registerEvent
    $(document.body).on("click", s".myImportShow", "", (y: Element) => {
      val dict = $(y).dataRow.toJDS
      importShow(dict)
    })
    $(s"#${importModalId}").on("shown.bs.modal", () => {
      $(s"#${importModalId} #${formId}").bv.revalidateField("fileName")
    })
    $(document.body).on("click", s"#${importModalId} .myImport", "", (y: Element) => {
      importRun
    })
  }

  def importRun = {
    val modalId = importModalId
    val bv = $(s"#${importModalId} #${formId}").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val data = $(s"#${importModalId} #${formId}").serialize()
      val index = layer.alert(Tool.myElement, Tool.layerOptions)
      val url = g.jsRoutes.controllers.MatrixFileDataController.importRun().url.toString
      Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        layer.close(index)
        $(s"#${modalId}").modal("hide")
        bv.resetForm(true)
        val options = SwalOptions(
          `type` = "success",
          title = messages("success"),
          text = messages("ImportedSuccessfully")
        )
        Swal.swal(options)
      }
    }
  }


  def importShow(dict: js.Dictionary[String]) = {
    val fillDict = dict.map { case (k, v) =>
      val trueV = k match {
        case "fileName" => dict("dataFileName").fileNamePrefix
        case _ => v
      }
      (k, trueV)
    }.toJSDictionary
    Tool.fillByNames(fillDict, $(s"#${importModalId} #form"))
    val missionName=$("#missionName span").text().trim
    $(s"#${importModalId} #${formId} :input[name='originalFileName']").`val`(s"mission/${missionName}/${dict("fileName")}")
    val tagComponent = TagComponent.Component().renderIntoDOM(document.querySelector(s"#${importModalId} .tag")).
      setState(TagComponent.State(dict("tags")))
    $(s"#${importModalId}").modal("show")
  }

  override lazy val operateColumn = js.Array(
    ColumnOptions.field("operate").title(messages("operations")).formatter(operateFmt).filterControl("clear")
  )

  override def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>

      val fileName = row("fileName")
      val downloadUrl = g.jsRoutes.controllers.MissionController.downloadResultFile().url.toString
      val downloadStr = a(title := messages("download"),
        href := s"${downloadUrl}?missionId=${getMissionId}&fileName=${fileName}", cursor.pointer,
        span(em(cls := "fa fa-download"))
      )
      val importStr = a(title := messages("exportToDataRepositories"), dataRow := s"${JSON.stringify(row)}", `class` := "myImportShow", cursor.pointer,
        target := "_blank", span(em(cls := "fa fa-clone"))
      )
      val detailViewStr = a(title := messages("viewDetails"), `class` := "myViewFile", dataValue := s"${row("fileName")}",
        span(em(cls := "fa fa-eye"))
      )

      val rs = if (List(".pdf", ".zip", ".svg", ".json").exists(x => row("fileName").toString.endsWith(x))) {
        List(downloadStr)
      } else List(detailViewStr, importStr, downloadStr)
      rs.mkString("&nbsp;")
  }

  override def refreshFileInfo(missionId: String) = {
    val url = g.jsRoutes.controllers.MissionController.getResultFileInfo().url.toString
    Ajax.get(url = s"${url.noCache}&missionId=${missionId}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val headerMap = SeqMap("fileName" -> messages("file"), "rowNum" -> messages("rowsInDataFile"), "intro" -> messages("note"))
      val columnNames = headerMap.keyList
      val columns = columnNames.map { columnName =>
        val fmt = columnName
        val title = headerMap.getOrElse(columnName, columnName)
        ColumnOptions.field(columnName).title(title).sortable(true)
      }.toJSArray.concat(operateColumn)
      val options = TableOptions.data(rs).columns(columns).pagination(false)
      $(s"#${tableId}").bootstrapTable(options)
    }
  }

  def getMissionId = {
    g.missionId.toString
  }

  def bootStrapValidator = {
    def dataF: js.Function = (validator: BootstrapValidator) => {
      js.Dictionary(
        "kind" -> MetDataKind.name
      )
    }

    val maxNumber = Double.MaxValue
    val url = g.jsRoutes.controllers.MatrixFileDataController.fileNameNonExistCheck().url.toString
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "fileName" ->{
          val info=messages("fileName")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("exist")}",
                "url" -> url,
                "delay" -> 1000,
                "type" -> "POST",
                "data" -> dataF
              ),
            )
          )
        } ,
      )
    )
    $(s"#${importModalId} #${formId}").bootstrapValidator(dict)
  }


}
